import 'dart:async';
import 'package:flutter/material.dart';
import 'kq_small_button.dart';

class KqCountDownButton extends StatefulWidget {
  /// 倒计时数值
  final int countDownValue;

  /// 非计时时显示的按钮文字
  final String text;

  /// 点击后的回调
  final Function(CountDownButtonState state)? onTap;

  const KqCountDownButton({
    super.key,
    required this.countDownValue,
    required this.text,
    this.onTap,
  });

  @override
  State<StatefulWidget> createState() => CountDownButtonState();
}

class CountDownButtonState extends State<KqCountDownButton> {
  /// 当前进度文本
  late String _text;

  /// 按钮是否不可用
  bool _disabled = false;

  /// 计时器
  Timer? timer;

  @override
  void initState() {
    super.initState();
    _text = widget.text;
  }

  void startTimer() {
    int count = 0;
    //计时器，每1秒执行一次
    const period = Duration(seconds: 1);
    timer = Timer.periodic(period, (timer) {
      count++;
      num max = widget.countDownValue;
      //计时器结束条件
      if (widget.countDownValue == 0 || count >= max) {
        timer.cancel();
        if (mounted) {
          setState(() {
            _text = widget.text;
            _disabled = false;
          });
        }
      } else {
        if (mounted) {
          setState(() {
            _text = (widget.countDownValue - count).toString();
            _disabled = true;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    //退出时关闭计时器防止内存泄露
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return KqSmallButton(
      disabled: _disabled,
      title: _text,
      onTap: (disabled) {
        if (widget.onTap != null && !disabled) {
          widget.onTap!(this);
        }
      },
    );
  }
}
